using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace HOPE {
	// mengontrol jalannya animasi

	struct AnimationPlayer {
		//mencari animasi mana yang sedang berjalan

		public Animation Animation {
			get { return animation; }
		}
		Animation animation;

		//mencari index dari frame yang sedang berjalan dalam animasi

		public int FrameIndex {
			get { return frameIndex; }
		}
		int frameIndex;

		//jumlah waktu dalam detik yang ditampilkan oleh current frame
		private float time;

		//mencari titik origin dari texture yang terletak di tengah tiap frame
		public Vector2 Origin {
			get { return new Vector2(Animation.FrameWidth / 2.0f, Animation.FrameHeight); }
		}

		//memulai atau melanjutkan kembali jalannya animasi
		public void PlayAnimation (Animation animation) {
			//jika animasi telah berjalan,tidak perlu di restart
			if (Animation == animation)
				return;

			//memulai animasi baru
			this.animation = animation;
			this.frameIndex = 0;
			this.time = 0.0f;
		}

		//Advances the time position and draws the current frame of the animation.
		public void Draw (GameTime gameTime, SpriteBatch spriteBatch, Vector2 position, SpriteEffects spriteEffects) {
			if (Animation == null)
				throw new NotSupportedException("ga ada animasi yang jalan");

			//proses jalannya waktu
			time += (float)gameTime.ElapsedGameTime.TotalSeconds;
			while (time > Animation.FrameTime) {
				time -= Animation.FrameTime;

				//Advance the frame index; looping or clamping as appropriate.
				if (Animation.IsLooping) {
					frameIndex = (frameIndex + 1) % Animation.FrameCount;
				}
				else {
					frameIndex = Math.Min(frameIndex + 1, Animation.FrameCount - 1);
				}
			}

			// Calculate the source rectangle of the current frame.
			Rectangle source = new Rectangle(FrameIndex * Animation.Texture.Height, 0, Animation.Texture.Height, Animation.Texture.Height);

			//Draw the current frame
			spriteBatch.Draw(Animation.Texture, position, source, Color.White, 0.0f, Origin, 1.0f, spriteEffects, 0.0f);
		}
	}
}
